﻿using System;
using System.ServiceModel;
using System.Threading;
using APMABusinessLogicCoreLib;

namespace APMAConsoleServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***WCF Host***");
            using (var serviceHost = new ServiceHost(typeof(BusinessLogicCore)))
            {
                serviceHost.Open();

                DisplayHostInfo(serviceHost);

                var stateTimer = new Timer(SaveChartData, "Tick", 0, 86400000);
                
                Console.WriteLine("The service is ready!");
                Console.WriteLine("Press Enter to terminate.");
                Console.ReadLine();
                stateTimer.Dispose();
            }
        }

        static void SaveChartData(Object stateInfo)
        {
            try
            {
                Console.WriteLine("Saving chart data.");

                var blc = new BusinessLogicCore();
                blc.SaveChartData();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while saving chart data.");
            }
        }

        static void DisplayHostInfo(ServiceHost serviceHost)
        {
            Console.WriteLine();
            Console.WriteLine("***Host Info***");

            foreach (var el in serviceHost.Description.Endpoints)
            {
                Console.WriteLine("Address: {0}", el.Address);
                Console.WriteLine("Binding: {0}", el.Binding.Name);
                Console.WriteLine("Contract: {0}", el.Contract.Name);
                Console.WriteLine();
            }

            Console.WriteLine("***************");
        }
    }
}
